package cn.innosmart.aq.view.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.sleepbot.datetimepicker.time.RadialPickerLayout;
import com.sleepbot.datetimepicker.time.TimePickerDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.AssignBoxAdapter;
import cn.innosmart.aq.bean.BoxBean;
import cn.innosmart.aq.bean.Reminder;
import cn.innosmart.aq.customize.datetimepicker.RepeatDialog;
import cn.innosmart.aq.customize.datetimepicker.WeekChooseView;
import cn.innosmart.aq.customize.switchbutton.CheckSwitchButton;
import cn.innosmart.aq.reminder.ReminderManager;
import cn.innosmart.aq.util.FragmentManagerTool;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SharedUtil;

public class ReminderFragment extends BaseFragment implements INetworkInteractUtil, TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
    public static final String DATEPICKER_TAG = "datepicker";
    public static final String TIMEPICKER_TAG = "timepicker";
    private final int MODIFY = 1;
    private NetworkInteractUtil networkInteractUtil;
    private ListView lvAssignBox;
    private TextView tvEmpty;
    private Toolbar toolbar;
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentManagerTool.popBackStackFragment(getActivity().getSupportFragmentManager());
        }
    };
    private Menu menus;
    private ArrayList<BoxBean> boxBeans;
    //    private HashMap<>
    private ArrayList<String> assignedBoxs;
    private AssignBoxAdapter assignBoxAdapter;
    private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            BoxBean boxBean = (BoxBean) buttonView.getTag();
            if (isChecked) {
                if (!assignedBoxs.contains(boxBean.getHubId()))
                    assignedBoxs.add(boxBean.getHubId());
            } else {
                if (assignedBoxs.contains(boxBean.getHubId()))
                    assignedBoxs.remove(boxBean.getHubId());
            }
        }
    };
    private View view;
    private LinearLayout llDate;
    private LinearLayout llTime;
    private LinearLayout llRepeat;
    private TextView tvDate;
    private TextView tvTime;
    private TextView tvRepeat;
    private EditText etReminderTitle;
    private EditText etReminderContent;
    private Calendar calendar;
    private TimePickerDialog timePickerDialog;
    private DatePickerDialog datePickerDialog;
    private CheckBox cbEnable;
    private Spinner spRepeatType;
    private Spinner spRepeatPeriodic;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ll_date:
                    setDate();
                    break;
                case R.id.ll_time:
                    setTime();
                    break;
                case R.id.ll_repeat:
//                    showRepeatDialog();
                    break;
            }
        }
    };
    private Reminder reminder;
    private int flag = 0;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_save:
                    saveReminder();
                    break;
            }
            return true;
        }
    };
    private CheckSwitchButton repeatSwitch;
    private LinearLayout llSetRepeat;
    private WeekChooseView weekChoose;

    private void showRepeatDialog() {
        final RepeatDialog repeatDialog = new RepeatDialog(getActivity());
        repeatDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                repeatDialog.dismiss();
            }
        });
        repeatDialog.setNegativeButton(R.string.cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                repeatDialog.dismiss();
            }
        });
        repeatDialog.show();
    }

    private void saveReminder() {
        String title = etReminderTitle.getText().toString().trim();
        String content = etReminderContent.getText().toString().trim();
        String date = tvDate.getText().toString().trim();
        String time = tvTime.getText().toString().trim();
//        String repeat = tvRepeat.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            showToast(getString(R.string.reminder_title_no_empty));
            return;
        }
        if (TextUtils.isEmpty(content)) {
            showToast(getString(R.string.reminder_content_no_empty));
            return;
        }
        if (TextUtils.isEmpty(date)) {
            showToast(getString(R.string.reminder_date_no_empty));
            return;
        }
        if (TextUtils.isEmpty(time)) {
            showToast(getString(R.string.reminder_time_no_empty));
            return;
        }
//        if (TextUtils.isEmpty(repeat)) {
//            showToast("备忘提醒的重复设置不能为空!");
//            return;
//        }
        reminder.title = title;
        reminder.date = date;
        reminder.time = time;
//        reminder.repeat = repeat;
        reminder.content = content;
        if (cbEnable.isChecked()) {
            //SetAlarm
            reminder.isEnable = true;
            if (flag == MODIFY) {
                SharedUtil.getInstance().updateReminder(reminder);
            } else {
                SharedUtil.getInstance().addReminder(reminder);
            }
            ReminderManager.createAlarm(getActivity(), reminder);
        } else {
            reminder.isEnable = false;
            if (flag == MODIFY) {
                SharedUtil.getInstance().updateReminder(reminder);
            } else {
                SharedUtil.getInstance().addReminder(reminder);
            }
        }
        FragmentManagerTool.popBackStackFragment(getActivity().getSupportFragmentManager());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        view = inflater.inflate(R.layout.activity_reminder, null);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }

    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.drawable.toolbar_back);
        if (flag == 1) {
            toolbar.setTitle(getActivity().getString(R.string.toolbar_modify_reminder));
        } else {
            toolbar.setTitle(getActivity().getString(R.string.toolbar_add_reminder));
        }
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(onNavigationClickListener);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }

    @Override
    public void onStart() {
        super.onStart();
        Bundle bundle = getArguments();
        if (bundle != null)
            flag = bundle.getInt("flag");
        if (flag == 1) {
            reminder = bundle.getParcelable("reminder");
        } else {
            reminder = new Reminder();
        }
        if (reminder.repeatDatas == null) {
            reminder.repeatDatas = new HashMap<>();
        }
        setBar();
        assignViews();
        assignListeners();
    }
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    private void assignViews() {
        weekChoose = (WeekChooseView) view.findViewById(R.id.week_choose);
        llSetRepeat = (LinearLayout) view.findViewById(R.id.ll_set_repeat);
        repeatSwitch = (CheckSwitchButton) view.findViewById(R.id.repeat_switch);
        spRepeatType = (Spinner) view.findViewById(R.id.sp_repeat_type);
        spRepeatPeriodic = (Spinner) view.findViewById(R.id.sp_repeat_periodic);
        calendar = Calendar.getInstance();
        cbEnable = (CheckBox) view.findViewById(R.id.cb_enable);
        llDate = (LinearLayout) view.findViewById(R.id.ll_date);
        llTime = (LinearLayout) view.findViewById(R.id.ll_time);
        llRepeat = (LinearLayout) view.findViewById(R.id.ll_repeat);
        tvDate = (TextView) view.findViewById(R.id.tv_date);
        tvTime = (TextView) view.findViewById(R.id.tv_time);
        tvRepeat = (TextView) view.findViewById(R.id.tv_repeat);
        etReminderTitle = (EditText) view.findViewById(R.id.et_reminder_title);
        etReminderContent = (EditText) view.findViewById(R.id.et_reminder_content);
        timePickerDialog = TimePickerDialog.newInstance(this, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true, false);
        datePickerDialog = DatePickerDialog.newInstance(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), true);
        cbEnable.setChecked(reminder.isEnable);
        etReminderTitle.setText(reminder.title);
        etReminderContent.setText(reminder.content);
        tvDate.setText(reminder.date);
        tvTime.setText(reminder.time);
        //默认选中周，默认选中周四
        spRepeatType.setSelection(1);
        weekChoose.setChecked(calendar.get(Calendar.DAY_OF_WEEK) - 1, true);
        reminder.repeatDatas.put(calendar.get(Calendar.DAY_OF_WEEK) - 1, Long.valueOf((spRepeatPeriodic.getSelectedItemPosition() + 1) * 7 * 24 * 60 * 60 * 1000));
        spRepeatType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    weekChoose.setVisibility(View.GONE);
                    if (reminder.repeatDatas == null)
                        reminder.repeatDatas = new HashMap<Integer, Long>();
                    reminder.repeat = Reminder.EVERYPERIODICDAY;
                    reminder.repeatDatas.put(7, Long.valueOf((spRepeatPeriodic.getSelectedItemPosition() + 1) * 24 * 60 * 60 * 1000));
                    tvRepeat.setText(String.format(getActivity().getString(R.string.periodic_every_day), spRepeatPeriodic.getSelectedItemPosition() + 1));
                } else {
                    weekChoose.setVisibility(View.VISIBLE);
                    if (reminder.repeatDatas == null)
                        reminder.repeatDatas = new HashMap<Integer, Long>();
                    if (reminder.repeatDatas.containsKey(7))
                        reminder.repeatDatas.remove(7);
                    reminder.repeat = Reminder.EVERYOERIODICWEEK;
                    Iterator iterator = reminder.repeatDatas.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry entry = (Map.Entry) iterator.next();
                        entry.setValue(Long.valueOf((spRepeatPeriodic.getSelectedItemPosition() + 1) * 7 * 24 * 60 * 60 * 1000));
                    }
                    tvRepeat.setText(selectCurrentWeek());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spRepeatPeriodic.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                int periodic = position + 1;
                if (reminder.repeatDatas == null)
                    reminder.repeatDatas = new HashMap<Integer, Long>();
                if (reminder.repeat == Reminder.EVERYPERIODICDAY) {
                    Iterator iterator = reminder.repeatDatas.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry entry = (Map.Entry) iterator.next();
                        entry.setValue(Long.valueOf(periodic * 24 * 60 * 60 * 1000));
                    }
                } else if (reminder.repeat == Reminder.EVERYOERIODICWEEK) {
                    Iterator iterator = reminder.repeatDatas.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry entry = (Map.Entry) iterator.next();
                        entry.setValue(Long.valueOf(periodic * 7 * 24 * 60 * 60 * 1000));
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        repeatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    llSetRepeat.setVisibility(View.VISIBLE);
                    if (reminder.repeatDatas.containsKey(7)) {
                        //显示每天的界面
                        tvRepeat.setText(String.format(getActivity().getString(R.string.periodic_every_day), spRepeatPeriodic.getSelectedItemPosition() + 1));
                    } else {
                        //显示每周的界面
                        tvRepeat.setText(selectCurrentWeek());
                    }

                } else {
                    //清空数据
                    llSetRepeat.setVisibility(View.GONE);
                    tvRepeat.setText(R.string.repeat_never);
                    reminder.repeat = Reminder.NERVER;

                }
            }
        });
        weekChoose.setOnRepeatStatusChanged(new WeekChooseView.OnRepeatStatusChanged() {
            @Override
            public void onCheckChanged(int position, boolean isChecked) {
                int periodic = spRepeatPeriodic.getSelectedItemPosition() + 1;
                if (reminder.repeatDatas == null) {
                    reminder.repeatDatas = new HashMap<Integer, Long>();
                }
                if (isChecked)
                    reminder.repeatDatas.put(position, Long.valueOf(periodic * 7 * 24 * 60 * 60 * 1000));
                else {
                    if (reminder.repeatDatas.containsKey(position)) {
                        reminder.repeatDatas.remove(position);
                    }
                }
                tvRepeat.setText(selectCurrentWeek());
            }
        });
    }

    //    private int selectCurrentWeek() {
//        Calendar calendar = Calendar.getInstance();
//        calendar.get(Calendar.DAY_OF_WEEK);
////        calendar.setTimeInMillis(System.currentTimeMillis());
//        return 1;
//    }
    private String selectCurrentWeek() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(R.string.every_periodic);
        if (reminder.repeatDatas == null) {
            reminder.repeatDatas = new HashMap<>();
        }
        if (reminder.repeatDatas.containsKey(1)) {
            stringBuilder.append(R.string.reminder_monday);
        }
        if (reminder.repeatDatas.containsKey(2)) {
            stringBuilder.append(R.string.reminder_tuesday);
        }
        if (reminder.repeatDatas.containsKey(3)) {
            stringBuilder.append(R.string.reminder_wensday);
        }
        if (reminder.repeatDatas.containsKey(4)) {
            stringBuilder.append(R.string.reminder_thursday);
        }
        if (reminder.repeatDatas.containsKey(5)) {
            stringBuilder.append(R.string.reminder_friday);
        }
        if (reminder.repeatDatas.containsKey(6)) {
            stringBuilder.append(R.string.reminder_saturday);
        }
        if (reminder.repeatDatas.containsKey(0)) {
            stringBuilder.append(R.string.reminder_sunday);
        }
        if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') {
            stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), "");
        }
        return stringBuilder.toString();
    }


    private void assignListeners() {
        llDate.setOnClickListener(onClickListener);
        llTime.setOnClickListener(onClickListener);
        llRepeat.setOnClickListener(onClickListener);
    }

    public void setTime() {
        timePickerDialog.setVibrate(true);
        timePickerDialog.setCloseOnSingleTapMinute(false);
        if (!timePickerDialog.isAdded()) {
            timePickerDialog.show(getActivity().getSupportFragmentManager(), TIMEPICKER_TAG);
        }
    }


    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    public void setDate() {
        datePickerDialog.setVibrate(true);
        datePickerDialog.setYearRange(1985, 2028);
        datePickerDialog.setCloseOnSingleTapDay(false);
        if (!datePickerDialog.isAdded()) {
            datePickerDialog.show(getActivity().getSupportFragmentManager(), DATEPICKER_TAG);
        }

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_reminder, menu);
        menus = menu;
        super.onCreateOptionsMenu(menu, inflater);
    }

    private void getData() {

    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
    }


    @Override
    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
        tvTime.setText(hourOfDay + ":" + minute);
        reminder.hour = hourOfDay;
        reminder.minitue = minute;
    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        datePickerDialog.getSelectedDay();
        reminder.year = year;
        reminder.month = month;
        reminder.day = day;
        tvDate.setText(year + "/" + (month + 1) + "/" + day);
    }
}
